##用于introduction的数据支撑
from util import *
import pandas as pd
import numpy as np

# 设置显示选项
pd.set_option('display.max_rows', None)      # 显示完整行数
pd.set_option('display.max_columns', None)   # 显示完整列数
pd.set_option('display.width', None)         # 扩展显示宽度
pd.set_option('display.max_colwidth', None)  # 显示完整列宽



def get_percent_of_two_way_call(csv_file_path):
    pd_all=pd.read_csv(csv_file_path)
    pd_without_http=pd_all[pd_all["rpctype"]!="http"]
    all_call_times=len(pd_without_http)
    pd_with_mq=pd_all[pd_all["rpctype"]=="mq"]
    mq_call_times=len(pd_with_mq)
    two_way_call_percent=1-mq_call_times/all_call_times
    print(f"双向调用的比例: {two_way_call_percent}")
    
    
def get_percent_of_full_graph(csv_file_path):
    pd_all=pd.read_csv(csv_file_path)
    # 按service分组，统计不同traceid出现的次数
    service_to_call_pd = pd_all.groupby('service')['traceid'].value_counts().reset_index(name='count')
    # print(f"{len(service_to_call_pd)}")
    # 计算每个service的调用次数
    service_to_call_times_pd = service_to_call_pd.groupby('service')['traceid'].count().reset_index(name='call_times')
    # 计算每个service最大调用图
    service_to_max_call_graph_pd=service_to_call_pd.groupby('service')['count'].max().reset_index(name='max_call_graph')
    # 筛选出请求次数大于1的service，并且call graph 最大规模大于1的service
    filtered_services = service_to_max_call_graph_pd[(service_to_call_times_pd['call_times'] >1)  & (service_to_max_call_graph_pd['max_call_graph']>1)]['service']
    
    # 仅保留符合条件的service的数据
    filtered_service = service_to_call_pd[service_to_call_pd['service'].isin(filtered_services)]
    all_request_num=len(filtered_service)
    # 找出每个service中出现次数最高的traceid及其数量
    max_value = filtered_service.groupby('service')['count'].transform("max")
    max_counts_pd=filtered_service[filtered_service['count']==max_value]
    max_request_num=len(max_counts_pd)
    print(f"请求为full call graph的比例{max_request_num/all_request_num} with max:{max_request_num} all:{all_request_num}")
    
    
def   get_percent_of_ms_to_service(csv_file_path):
    pd_all=pd.read_csv(csv_file_path)
    ms_to_service_count_pd=pd_all.groupby("dm")['service'].value_counts().reset_index(name='count')
    # print(ms_to_service_count_pd)
    ms_number=pd_all['dm'].nunique()
    # print(len(ms_to_service_count_pd))
    # print(pd_all['dm'].nunique())
    all_service_to_ms_number=len(ms_to_service_count_pd)
    ms_to_one_service_num=ms_to_service_count_pd[ms_to_service_count_pd['count']==1]['dm'].nunique()
    print(f"每个Microservice平均被{all_service_to_ms_number/ms_number}个service调用，MS被单个MS调用的比例为：{ms_to_one_service_num/ms_number}")
   
   
file_path="datas/CallGraph_cleaned_0.005_history.csv"
get_percent_of_two_way_call(file_path)
get_percent_of_full_graph(file_path)
get_percent_of_ms_to_service(file_path)